from Helpers import langRe
from highlight import ID_RE

__author__ = 'deadmoroz'

class LanguageCompiler(object):
    def compile(self, language):
        self.__compileMode(language.defaultMode, language, True)

    def __compileMode(self, mode, language, is_default):
        if mode.compiled:
            return
        if not is_default:
            mode.beginRe = langRe(language, mode.begin if mode.begin else r'|\\B|\\b')
            if  not mode.end and not mode.endsWithParent:
                mode.end = r'|\\B|\\b'
            if mode.end:
                mode.endRe = langRe(language, mode.end)
        if mode.illegal:
            mode.illegalRe = langRe(language, mode.illegal)
        if mode.keywords:
            mode.lexemsRe = langRe(language, mode.lexems if mode.lexems else ID_RE)

        for key in mode.keywords:
            if mode.keywords[key] is dict:
                mode.keywordGroups = mode.keywords
            else:
                mode.keywordGroups = {"keyword" : mode.keywords}

        mode.compiled = True
        for childMode in mode.contains:
            self.__compileMode(childMode, language, False)
        if mode.starts:
            self.__compileMode(mode.starts, language, False)